package com.boby.homecamera.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.boby.homecamera.adapter.VideoAdapter
import com.boby.lib_common.extens.dp
import com.boby.lib_common.util.BLog
import kotlin.math.abs

class MyRecyclerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : RecyclerView(context, attrs) {
    private val TAG  = "MyRecyclerView"

    private var startX = 0f
    private var startY = 0f
    private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop

    var lastTouchTime = 0L
    private set
    var isUserScroll = false
    var isProgrammaticScroll = false

    var scrollCallBack: ((scrollOffset: Int) -> Unit?)? = null
    var totalHeight = 0


    init {
        addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

//364927
//703790
//                BLog.d("MyRecyclerView", "ScrollOffset 当前已上滑距离: $offset px")
//                BLog.d("MyRecyclerView", "Scroll dx: $dx, dy: $dy")
                when {
                    isUserScroll -> {
//                        BLog.d("MyRecyclerView", "这是用户手势滑动")
//                        val offset = recyclerView.computeVerticalScrollOffset()
                        scrollCallBack?.invoke(0)

                    }

                    isProgrammaticScroll -> {
//                        BLog.d("MyRecyclerView", "这是调用 scrollToPositionWithOffset() 导致的滚动")

                    }

                    else -> {
//                        BLog.d("MyRecyclerView", "不确定来源（可能是惯性 or 系统处理）")
                    }
                }
            }
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_DRAGGING -> {
                        isUserScroll = true
                        isProgrammaticScroll = false
                    }

                    RecyclerView.SCROLL_STATE_SETTLING -> {
                        // 惯性滑动中（可能是拖动或程序触发）
                    }

                    RecyclerView.SCROLL_STATE_IDLE -> {
                        isUserScroll = false
                        isProgrammaticScroll = false
                    }
                }
            }
        })


    }


    override fun onTouchEvent(e: MotionEvent?): Boolean {
        lastTouchTime = System.currentTimeMillis()
        return super.onTouchEvent(e)
    }
    var maxScrollPx: Int = Int.MAX_VALUE

    override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
        when (e.action) {
            MotionEvent.ACTION_DOWN -> {
                startX = e.x
                startY = e.y
                // 清除旧的滚动状态
                parent.requestDisallowInterceptTouchEvent(false)
            }

            MotionEvent.ACTION_MOVE -> {
                val dx = abs(e.x - startX)
                val dy = abs(e.y - startY)

                // 如果竖向滑动大于横向滑动，则拦截事件，交给 RecyclerView 处理
                if (dy > dx && dy > touchSlop) {
                    parent.requestDisallowInterceptTouchEvent(true)
                    return true
                }
            }

            MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                // 重置拦截状态
                parent.requestDisallowInterceptTouchEvent(false)
            }
        }

        return super.onInterceptTouchEvent(e)
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        return super.dispatchTouchEvent(ev)
    }

    fun getCenterItemOffset(): Pair<Int, Int?> {
        var recyclerView = this
//        val layoutManager = recyclerView.layoutManager ?: return 0 to null
        val childCount = recyclerView.childCount
        if (childCount == 0) return 0 to null

        val rvCenter = recyclerView.height / 2f

//        var closestChild: View? = null
//        var minDistance = Int.MAX_VALUE
        var offset = 0
        var adapterPosition = RecyclerView.NO_POSITION
        var marginTop = 10f.dp()
        for (i in 0 until childCount) {
            val child = recyclerView.getChildAt(i) ?: continue
            if((child.top - marginTop) <= rvCenter && child.bottom >= rvCenter  ){
                recyclerView.getChildAdapterPosition(child)
                adapterPosition = recyclerView.getChildAdapterPosition(child)
                offset = (rvCenter - ( child.top - marginTop)).toInt()
//                BLog.d("MyRecyclerView", "index:$i,adapterPosition:$adapterPosition offset:$offset")
                return adapterPosition to offset
            }

        }

        return adapterPosition to offset
    }


}